import json
from os import urandom

import requests
from spider_xue.settings import FIFTEEN, FIVE
import time

from db import *
from spider_xue.new_ip import headers_list

fg = '2021-09-08'

# 十个交易日的斜率， 五分钟两的倍数 * 增加的点数， 十分钟倍数 * 增加的点数, 十五分钟倍数 * 点数  + 涨停和跌停比

all = stock_db.find({'use': 1})
url = 'http://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&beg=0&end=20500101&ut=fa5fd1943c7b386f172d6893dbfba10b&rtntype=6&secid={}&klt=5&fqt=1'
for i in all:
    symbol = i['symbol']
    if check_db.find_one({'symbol': symbol}):
        continue

    daykline = data_day_db.find_one({'symbol': symbol})
    daykline_items = daykline['item']
    k_dict = {}
    for index in range(11, len(daykline_items)+1):
        if daykline_items[index][0] < 1627781195000:
            continue
        date_key = time.strftime('%Y-%m-%d', time.localtime(int(daykline_items[index][0]/ 1000)))
        k1 = (daykline_items[index-6][5] - daykline_items[index-11][5]) / 5
        k2 = (daykline_items[index-1][5] - daykline_items[index-6][5]) / 5
        k_dict[date_key] = [k1, k2]
        print(date_key, daykline_items[index-11][5], daykline_items[index-6][5], daykline_items[index-1][5])
    
    code = symbol.replace('SH', '1.').replace('SZ', '0.')
    req = requests.get(url.format(code))
    g = req.json()
    klines = g['klines']
    preprice = g['prePrice']
    
    count_list = []
    count_dict = {}
    check_dict = {}
    for dataa in klines:
        if not dataa:
            continue
        line_data = dataa.strip().split(',')
        datte = line_data[0].split(' ')[0]
        if datte not in count_dict:
            count_dict[datte] = line_data[5]
            check_dict[datte] = line_data[8]
            count_list.append(datte)
        else:
            if line_data[5] > count_dict[datte]:
                count_dict[datte] = line_data[5]
                check_dict[datte] = line_data[8]
    for ddataaa in range(3, len(count_list)):
        
        pass

url5 = 'http://push2his.eastmoney.com/api/qt/stock/kline/get?fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&ut=7eea3edcaed734bea9cbfc24409ed989&klt=5&fqt=1&secid={}&beg=0&end=20500000&_=1635582273079'


def spider(ss, symbol, uurl, ip):
    sy = symbol.replace('SH', '1.').replace('SZ', '0.')
    headers = {"User-Agent": urandom.choice(headers_list)}
    headers['cookie'] = 'em_hq_fls=js; qgqp_b_id=20660913b8ac65856737edce0c59110a; intellpositionL=1215.35px; intellpositionT=1555px; st_si=14599186838984; HAList=a-sz-000725-%u4EAC%u4E1C%u65B9%uFF21%2Ca-sz-300059-%u4E1C%u65B9%u8D22%u5BCC%2Ca-sz-300680-%u9686%u76DB%u79D1%u6280%2Ca-sh-600318-%u65B0%u529B%u91D1%u878D; st_asi=delete; em-quote-version=topspeed; st_pvi=53532897904206; st_sp=2021-05-14%2020%3A06%3A10; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=4; st_psi=20211030162433120-113200301202-3659377157'
    ss.headers = headers
    ss.proxies = {"http": "http://{}".format(ip)}
    req = requests.get(url=uurl.format(sy), headers=headers)
    try:
        x = req.json()
        d = x['data']
        d['symbol'] = symbol
        east_five_db.update_one({'symbol': symbol}, {"$set": d}, upsert=True)
    except Exception as e:
        print(symbol, e)


def do():
    sees = requests.Session()
    sto = stock_db.find({"today": {"$in": [1, 2, 6, 8]}})
    x = []
    for i in sto:
        x.append(i['symbol'])
        # if not east_five_db.find_one({"symbol": i['symbol']}):
        #     spider(sees, i['symbol'], url5, "125.73.131.137:9091")
        #     time.sleep(2)
    print(x)

# do()


def cal():
    all = east_five_db.find()

    data = {}
    for sto in all:
        time_dict = {}
        time_list = []
        for line in sto['klines']:
            lines = line.split(",")
            time_key = lines[0].split(" ")[0]
            if time_key not in time_dict:
                time_dict[time_key] = lines
                time_list.append(time_key)
            else:
                if float(lines[6]) > float(time_dict[time_key][6]):
                    time_dict[time_key] = lines
        data[sto['symbol']] = {"time_dict": time_dict, 'time_list': time_list}

    time_symbol_dict = {}
    symbolxtime_dict = {}
    for k, dd in data.items():
        time_dict = dd['time_dict']
        time_list = dd['time_list']
        last = float(time_dict[time_list[0]][6])
        for t in time_list[1:]:
            if t not in time_symbol_dict:
                time_symbol_dict[t] = []
            if float(time_dict[t][6]) >= 2 * last and time_dict[t][1] < time_dict[t][2]:
                if time_dict[t][0].split(' ')[-1] in ['09:35', '09:40']:
                    continue
                time_symbol_dict[t].append(k)
                symbolxtime_dict[k+'x'+t] = time_dict[t]
            last = float(time_dict[t][6])

    output = {}
    for k, v in time_symbol_dict.items():
        ts = int(time.mktime(time.strptime(k, "%Y-%m-%d"))) * 1000

        zll = {}
        for sy in v:

            dayy = data_day_db.find_one({"symbol": sy})
            if not dayy:
                print(k, sy, 1111111111111111111)
                continue
            for ddday in range(0, len(dayy['item'])):
                if dayy['item'][ddday][0] == ts:
                    lp = ddday
                    break
            ct = 0
            for zzzz in dayy['item'][lp-10:lp]:
                if zzzz[7] <= 1:
                    ct += 1
            if ct >= 6:
                continue
            if len(dayy['item']) <= lp+1:
                continue
            if dayy['item'][lp-1][7] < -8:
                continue
            kkk = sy + 'x' + k
            enddd = dayy['item'][lp+1][5]
            lassst = dayy['item'][lp-1][5]

            price = float(symbolxtime_dict[kkk][2])

            if round((price-lassst) / lassst * 100, 2) > 8:
                continue

            d = round((enddd-price) / lassst * 100, 2)
            lddd = int(d)
            sto = stock_db.find_one({"symbol": k})
            if lddd not in zll:
                zll[lddd] = []

            zll[lddd].append(
                (sy, enddd, price, lassst, d, symbolxtime_dict[kkk]))
        output[k] = zll
        print(k)
        print(zll)
    print(output)
    return output
# cal()


def ca2():
    all = east_five_db.find()

    data = {}
    for sto in all:
        time_dict = {}
        time_list = []
        for line in sto['klines']:
            lines = line.split(",")
            time_key = lines[0].split(" ")[0]
            if time_key not in time_dict:
                time_dict[time_key] = lines
                time_list.append(time_key)
            else:
                if float(lines[6]) > float(time_dict[time_key][6]):
                    time_dict[time_key] = lines
        data[sto['symbol']] = {"time_dict": time_dict, 'time_list': time_list}

    time_symbol_dict = {}
    symbolxtime_dict = {}
    for k, dd in data.items():
        time_dict = dd['time_dict']
        time_list = dd['time_list']
        last = float(time_dict[time_list[0]][6])
        for t in time_list[1:]:
            if t not in time_symbol_dict:
                time_symbol_dict[t] = []
            if float(time_dict[t][6]) >= 2 * last and time_dict[t][1] < time_dict[t][2]:
                if time_dict[t][0].split(' ')[-1] in ['09:35', '09:40']:
                    continue
                time_symbol_dict[t].append(k)
                symbolxtime_dict[k+'x'+t] = time_dict[t]
            last = float(time_dict[t][6])

    output = {}
    for k, v in time_symbol_dict.items():
        ts = int(time.mktime(time.strptime(k, "%Y-%m-%d"))) * 1000

        zll = {}
        for sy in v:

            dayy = data_day_db.find_one({"symbol": sy})
            if not dayy:
                print(k, sy, 1111111111111111111)
                continue
            for ddday in range(0, len(dayy['item'])):
                if dayy['item'][ddday][0] == ts:
                    lp = ddday
                    break
            ct = 0
            for zzzz in dayy['item'][lp-10:lp]:
                if zzzz[7] <= 1:
                    ct += 1
            if ct >= 6:
                continue
            if len(dayy['item']) <= lp+1:
                continue
            if dayy['item'][lp-1][7] < -8:
                continue
            kkk = sy + 'x' + k
            enddd = dayy['item'][lp+1][5]
            lassst = dayy['item'][lp-1][5]

            price = float(symbolxtime_dict[kkk][2])

            if round((price-lassst) / lassst * 100, 2) > 8:
                continue

            d = round((enddd-price) / lassst * 100, 2)
            lddd = int(d)
            sto = stock_db.find_one({"symbol": k})
            if lddd not in zll:
                zll[lddd] = []

            zll[lddd].append(
                (sy, enddd, price, lassst, d, symbolxtime_dict[kkk]))
        output[k] = zll
        print(k)
        print(zll)
    print(output)
    return output